package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.shiro.ShiroUser;
import cn.stylefeng.guns.base.shiro.annotion.Permission;
import cn.stylefeng.guns.modular.system.controller.dto.BothSaleCommitTask;
import cn.stylefeng.guns.modular.system.controller.dto.IndentOrderTask;
import cn.stylefeng.guns.modular.system.entity.*;
import cn.stylefeng.guns.modular.system.model.params.BothSaleCommitAuditParam;
import cn.stylefeng.guns.modular.system.model.params.BothSaleCommitCheckParam;
import cn.stylefeng.guns.modular.system.model.params.IndentOrderCheckParam;
import cn.stylefeng.guns.modular.system.service.BothSaleCommitAuditService;
import cn.stylefeng.guns.modular.system.service.BothSaleCommitCheckService;
import cn.stylefeng.guns.modular.system.service.BothSaleCommitService;
import cn.stylefeng.guns.sys.core.shiro.ShiroKit;
import cn.stylefeng.guns.sys.core.util.utility.StatusCode;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 两地销售审核表控制器
 *
 * @author 小飞
 * @Date 2019-07-11 08:04:08
 */
@Controller
@RequestMapping("/bothSaleCommitCheck")
public class BothSaleCommitCheckController extends BaseController {

    private String PREFIX = "/bothSaleCommitCheck";

    @Autowired
    private BothSaleCommitCheckService bothSaleCommitCheckService;
    @Resource
    private TaskService taskService;
    @Resource
    private BothSaleCommitAuditService bothSaleCommitAuditService;
    @Autowired
    private UserService userService;
    @Autowired
    private BothSaleCommitService bothSaleCommitService;
    @Autowired
    private DeptService deptService;

    /**
     * 跳转到主页面
     *
     * @author 小飞
     * @Date 2019-07-11
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/bothSaleCommitCheck.html";
    }

    /**
     * 新增页面
     *
     * @author 小飞
     * @Date 2019-07-11
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/bothSaleCommitCheck_add.html";
    }

    /**
     * 编辑页面
     *
     * @author 小飞
     * @Date 2019-07-11
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/bothSaleCommitCheck_edit.html";
    }

    /**
     * 新增接口
     *
     * @author 小飞
     * @Date 2019-07-11
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(BothSaleCommitCheckParam bothSaleCommitCheckParam) {
        this.bothSaleCommitCheckService.add(bothSaleCommitCheckParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author 小飞
     * @Date 2019-07-11
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(BothSaleCommitCheckParam bothSaleCommitCheckParam) {
        this.bothSaleCommitCheckService.update(bothSaleCommitCheckParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author 小飞
     * @Date 2019-07-11
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(BothSaleCommitCheckParam bothSaleCommitCheckParam) {
        this.bothSaleCommitCheckService.delete(bothSaleCommitCheckParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author 小飞
     * @Date 2019-07-11
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BothSaleCommitCheckParam bothSaleCommitCheckParam) {
        BothSaleCommitCheck detail = this.bothSaleCommitCheckService.getById(bothSaleCommitCheckParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author 小飞
     * @Date 2019-07-11
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(BothSaleCommitCheckParam bothSaleCommitCheckParam) {
        return this.bothSaleCommitCheckService.findPageBySpec(bothSaleCommitCheckParam);
    }

    @RequestMapping("/check")
    @ResponseBody
    public ResponseData check(BothSaleCommitAuditParam bothSaleCommitAuditParam) {

        BothSaleCommitAudit bothSaleCommitAudit = new BothSaleCommitAudit();
        BeanUtils.copyProperties(bothSaleCommitAuditParam, bothSaleCommitAudit);
        bothSaleCommitAudit.setAuditTime(new Date());
        bothSaleCommitAudit.setUserId(ShiroKit.getUserNotNull().getId());
        Task task = taskService.createTaskQuery().taskId(bothSaleCommitAuditParam.getTaskId()).singleResult();
        bothSaleCommitAudit.setProcessInstanceId(task.getProcessInstanceId());
        bothSaleCommitAuditService.save(bothSaleCommitAudit);

        //启动审核流程
        Map<String, Object> map = new HashMap<>();
        map.put("status", bothSaleCommitAuditParam.getAuditStatus());
        map.put("userId",bothSaleCommitAuditParam.getDistributorId());
        taskService.complete(task.getId(), map);

        return ResponseData.success(200, "审核成功", bothSaleCommitAudit);
    }

    @ResponseBody
    @RequestMapping("/getList")
    public LayuiPageInfo list() {
        List<Task> tasks = taskService.createTaskQuery().processDefinitionKey("both_sale_commit").taskCandidateUser(ShiroKit.getUserNotNull().getId() + "").list();
        if(tasks.size() == 0) {
            return new LayuiPageInfo();
        }


        //根据流程实例ID查询请假申请表单数据
        List<BothSaleCommitTask> bothSaleCommitTasks = tasks.stream().filter(task -> bothSaleCommitService.getByProcessInstanceId(task.getProcessInstanceId())!=null).map(task -> {
            BothSaleCommitTask bothSaleCommitTask = new BothSaleCommitTask();
            BeanUtils.copyProperties(bothSaleCommitService.getByProcessInstanceId(task.getProcessInstanceId()), bothSaleCommitTask);
            bothSaleCommitTask.setUserName(userService.getById(bothSaleCommitTask.getUserId()).getName());
            bothSaleCommitTask.setProcessInstanceId(task.getProcessInstanceId());
            if(StatusCode.SUCCESS.getVal() == bothSaleCommitService.getByProcessInstanceId(task.getProcessInstanceId()).getCheckCode()){
                bothSaleCommitTask.setStatus("审核成功");
            } else if(StatusCode.PENDING.getVal()==bothSaleCommitService.getByProcessInstanceId(task.getProcessInstanceId()).getCheckCode()){
                bothSaleCommitTask.setStatus("待审核");
            }
            bothSaleCommitTask.setTaskId(task.getId());
            return bothSaleCommitTask;
        }).collect(Collectors.toList());
        LayuiPageInfo result = new LayuiPageInfo();
        result.setCount(bothSaleCommitTasks.size());
        result.setData(bothSaleCommitTasks);
        return result;

//        /*Long addressId = addressRoleService.getOne(new QueryWrapper<AddressRole>()
//                .eq("user_id", ShiroKit.getUserNotNull().getId())).getAddressId();*/
//        Integer type = null;
//        if (ShiroKit.hasRole("订货单审核人员")) {
//            type = StatusCode.PENDING.getVal();
//        }else if (ShiroKit.hasRole("主管")){
//            type= StatusCode.INDENTSUCCESS.getVal();
//        }
//        return this.indentOrderCheckService.findPageBySpec(indentOrderCheckParam, type);
    }

    @RequestMapping("/orderDetail")
    public String bothSaleDetail(Model model, Long id, String taskId){


        //经销商登录名
        ShiroUser shiroUser =  ShiroKit.getUserNotNull();
        model.addAttribute("username",shiroUser.getName());

        //部门
        String deptName = deptService.getById(shiroUser.getDeptId()).getSimpleName();
        model.addAttribute("deptName",deptName);
//        IndentOrderCheck indentOrderCheck = indentOrderCheckService.getById(id);
//        Long indentId = indentOrderCheck.getIndetOrderId();
        model.addAttribute("id",id);
        model.addAttribute("taskId", taskId);
        return  PREFIX + "/bothSaleCommit.html";
    }

    @RequestMapping("/goBack")
    public String goBack() {
        return PREFIX + "/bothSaleCommitCheck.html";
    }
}


